package com.example.demo.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.AjaxResult;
import com.example.demo.common.TableDataInfo;
import com.example.demo.common.TokenService;
import com.example.demo.controller.base.BaseController;
import com.example.demo.domain.query.*;
import com.example.demo.domain.model.User;
import com.example.demo.mapping.UserMapping;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;



    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBodyQuery loginBodyQuery){

        //通过账号查询用户是否存在
        User user = userService.login(loginBodyQuery.getUsername());
        if (user == null){
            return AjaxResult.error(401,"用户不存在!");
        }

        //校验账号密码是否正确  -> 还没有学习密码加密 -> 先使用equals进行比较
        if (!user.getPassword().equals(loginBodyQuery.getPassword())){
            return AjaxResult.error(401,"密码有误!");
        }

        //添加时效性
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,7);

        //生成用户登录凭证
        String token = JWT.create().withAudience(user.getUserId().toString())//当前token的受众群体
                .withClaim("userId",user.getUserId())//需要加密的数据
                .withClaim("username",user.getUsername())//需要加密的数据
                .withExpiresAt(calendar.getTime())//设置有效期
                .sign(Algorithm.HMAC256(TokenService.TOKEN_SECRET));//密钥签名  - secret

        return AjaxResult.success("login success",token);
    }
    @GetMapping("/list")
    public TableDataInfo list(PageQuery pageQuery){
        Page<User> page = new Page<>(pageQuery.getPageNum(),pageQuery.getPageSize());
        Page<User> page1 = userService.page(page);
        return dataInfo(page1.getRecords(),page1.getTotal());
    }

    @GetMapping("/dtl/{id}")
    public AjaxResult dtl(@PathVariable Long id){
        User user = userService.getById(id);
        return AjaxResult.success(user);
    }

    @PostMapping
    public AjaxResult createUser(@RequestBody UserCreateQuery userCreateQuery){

        User createQuery = UserMapping.INSTANCE.toCreate(userCreateQuery);
        return toAjax(userService.save(createQuery)) ;
    }

    @PutMapping
    public AjaxResult updateUser(@RequestBody UserUpdateQuery userCreateQuery){

        User updateQuery = UserMapping.INSTANCE.toUpdate(userCreateQuery);
        return toAjax(userService.updateById(updateQuery)) ;
    }

    @DeleteMapping("/{userId}")
    public AjaxResult deleteUser(@PathVariable Long userId){

        return toAjax(userService.removeById(userId)) ;
    }

    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody UserStatusQuery userStatusQuery){

        User updateQuery = UserMapping.INSTANCE.toStatus(userStatusQuery);
        return toAjax(userService.updateById(updateQuery)) ;
    }


}
